<template>
  <div>
    <!-- -----------------------------------------------------基本信息-------------------------------------------------------------- -->
    <el-divider>基本信息</el-divider>
    <div class="dialog_left">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="200px" inline class="rule-form">
        <el-form-item label="采购单号" prop="acceptanceBase.purchaseId" v-if="parentFlag">
          <el-select v-model="purid" filterable @change="handlePurchaseListChange($event)" placeholder="请选择采购单号">
            <el-option v-for="item in purchaseList" :key="item.purchaseId" :label="item.purchaseNum"
              :value="item.purchaseId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="采购单号" v-else>
          <el-input v-model="parentList.purchaseNum" disabled class="el-select" />
        </el-form-item>

        <el-form-item label="验收标题" prop="acceptanceBase.acceptanceTitle" v-if="parentFlag">
          <el-input v-model="ruleForm.acceptanceBase.acceptanceTitle" placeholder="请输入验收标题" />
        </el-form-item>

        <el-form-item label="验收标题" v-else>
          <el-input disabled v-model="parentList.acceptanceTitle" class="el-select" />
        </el-form-item>

        <el-form-item label="验收类型" prop="acceptanceType" v-if="parentFlag">
          <el-select v-model="ruleForm.acceptanceType" filterable placeholder="请选择验收类型" @change="handleSelcetChange">
            <el-option v-for="item in optionsList" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="验收类型" v-else>
          <el-input v-model="parentList.acceptanceTypeName" disabled class="el-select" />
        </el-form-item>


        <el-form-item label="是否终验" prop="finalAcceptanceFlag">
          <el-select v-model="ruleForm.finalAcceptanceFlag" placeholder="请选择采购类型">
            <el-option label="是" value="0"></el-option>
            <el-option label="否" value="1"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="下步验收" prop="params.nextAcceptanceType" v-if="ruleForm.finalAcceptanceFlag == 1">
          <el-select v-model="ruleForm.params.nextAcceptanceType" filterable placeholder="请选择属性">
            <el-option v-for="item in optionsList" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="验收人" prop="params.nextAccepterId" v-if="ruleForm.finalAcceptanceFlag == 1">
          <el-select v-model="ruleForm.params.nextAccepterId" filterable placeholder="请选择属性">
            <el-option v-for="item in getuserList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注信息" style="100%" />
        </el-form-item>
      </el-form>
    </div>
    <!-- ---------------------------------------------------设备信息----------------------------------------------------------- -->
    <el-divider>设备信息</el-divider>
    <div class="dialog_table">
      <!-- -------------------------------------------新增验收 ----------------------------------------->
      <el-table :data="tableList" style="width: 100%" border @select="handleSelectionChange" ref="tableDataRefs"
        v-if="childcreateitemid == ''">
        <el-table-column label="序号" width="100">
          <template slot-scope="scope">
            <div> {{ scope.$index + 1 }} </div>
          </template>
        </el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="brand" label="品牌" />
        <el-table-column prop="model" label="规格型号" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="supplierName" label="供应商 " />
        <el-table-column prop="purchaseTime" label="购置日期" />
        <el-table-column type="selection" width="55" label="本次验收设备" v-if="childcreateitemid == ''" />
      </el-table>
      <!-- -------------------------------------------立即验收 ----------------------------------------->
      <el-table :data="parentList.purchaseEquipmentAccountVos" style="width: 100%" border
        @select="handleSelectionChange" ref="tableDataRefs" v-if="childcreateitemid">
        <el-table-column label="序号" width="100">
          <template slot-scope="scope">
            <div> {{ scope.$index + 1 }} </div>
          </template>
        </el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="brand" label="品牌" />
        <el-table-column prop="model" label="规格型号" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="supplierName" label="供应商 " />
        <el-table-column prop="purchaseTime" label="购置日期" />
        <el-table-column prop="acceptanceTypeName" label="最新验收" />
        <el-table-column prop="acceptanceTime" label="验收时间" />
      </el-table>
    </div>
    <!-- ---------------------------------------------------附件信息----------------------------------------------------------- -->
    <el-divider>附件信息</el-divider>
    <!-- <el-upload ref="upload" class="upload-demo" :headers="header_url" :action="action_url" :file-list="fileList"
      :limit="1" :on-success="handlesuccess" :on-remove="handleremove" :before-upload="beforeUpload" list-type="text"
      accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx">
      <el-button icon="el-icon-upload2" type="primary">上传附件</el-button>
      <div slot="tip" class="el-upload__tip">支持xls，xlsx ,.docx , .doc，.pdf，.jpg，.png格式，大小不超过50M</div>
    </el-upload> -->
    <FileUpload v-model="ruleForm.file" :limit="1" :fileSize="50" style="width:385px"
      :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
    </FileUpload>
    <!-- ---------------------------------------------------结果信息----------------------------------------------------------- -->
    <!-- {{ruleForm.acceAcceLevels}} -->
    <el-divider>验收标准</el-divider>
    <el-select v-model="ruleForm.acceAcceLevels" multiple collapse-tags placeholder="请选择验收标准（可多选）"
      @visible-change="handleVisibleChange">
      <el-option v-for="item in PurchaseCheckList" :key="item.acceptanceLevelId" :label="item.levelName"
        :value="item.acceptanceLevelId">
      </el-option>
    </el-select>
    <!-- ---------------------------------------------------结果信息----------------------------------------------------------- -->
    <el-divider>结果信息</el-divider>
    <div style="margin-left:20%">
      <!-- <div style="margin-bottom:1%">验收意见</div> -->
      <el-input type="textarea" :rows="5" placeholder="请输入验收意见" v-model.trim="ruleForm.view" maxlength="50"
        show-word-limit style="width:80%">
      </el-input>
    </div>


    <!-- ---------------------------------------------------通过，不通过及取消【按钮】----------------------------------------------------------- -->
    <div align="center" :style="{ 'margin-top': '25px' }">
      <el-button type="primary" @click="handleSubmitForm(0)">通过</el-button>
      <el-button type="danger" @click="handleSubmitForm(1)">不通过</el-button>
      <el-button @click="handleCloseForm">取消</el-button>
    </div>
  </div>
</template>

<script>
import { add, relatedtomePurchaseList, ImmediateDetail, ImmediateDetailPut } from '@/api/purchasing/equipment'
import { listDictionary } from '@/api/menu.js'//字典==>验收标题
import { getuserlist } from '@/api/equipment/equipment.js'//验收人
import { standardList as checkList } from '@/api/purchasing/equipment'// 验收标准
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  //采购单号信息-------------------------------------------------------
  acceptanceBase: {
    purchaseId: null, //采购ID
    purchaseNum: null, //采购编号
    purchaseTitle: null, //采购标题
    acceptanceTitle: null //验收标题
  },
  // 终验选择 （否） 时填写信息------------------------------------------------
  params: {
    nextAcceptanceType: "", //下一步验收类型
    nextAccepterId: "" //下一步验收人ID
  },
  // 设备信息表格，一次只能选择一台------------------------------------------
  accePurEquips: {},
  // 验收标准，可多选--------------------------------------------------
  acceAcceLevels: [],
  // 其他表单信息---------------------------------------------------------
  acceptanceType: "", //验收类型
  finalAcceptanceFlag: "0", //终验标志（0是 1否）
  remark: "", //备注
  file: "", //附件
  view: "",//验收意见
  status: "" //验收状态（0通过 1不通过）
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'detailedform',
  props: ['childcreateitemid'],
  data () {
    return {
      ruleForm: Object.assign({}, ruleForm),
      purchaseList: [],// 采购单号列表
      optionsList: [],// 验收类型和下步验收
      getuserList: [],// 验收人
      tableList: [],// 设备信息表格
      PurchaseCheckList: [],// 验收标准

      fileList: [],// 上传的文件数据，用于展示，没用的数据
      purid: '',// 没用的数据，用于绑定
      parentFlag: true,// 判断是否是立即验收开关
      parentList: {},// 立即验收的数据
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        'acceptanceBase.purchaseId': [
          { required: true, message: '请选择采购编号', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        'acceptanceBase.acceptanceTitle': [
          { required: true, message: '请输入验收标题', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        acceptanceType: [
          { required: true, message: '请选择验收类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        finalAcceptanceFlag: [
          { required: true, message: '请选择是否终验', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        'params.nextAcceptanceType': [
          { required: true, message: '请选择下步验收', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        'params.nextAccepterId': [
          { required: true, message: '请选择验收人', trigger: 'change' }
        ],
        fileNum: [
          { required: true, message: '请输入采购数量', trigger: 'blur' }
        ],
      }
    }
  },
  created () {
    this.getlist()
  },
  methods: {
    async getlist () {
      const { data: res1 } = await relatedtomePurchaseList();//采购单号接口
      const { data: res2 } = await listDictionary({ dictType: 'acceptance_level', status: 0 })// 验收类型接口
      const { data: res3 } = await getuserlist()// 验收人接口
      if (this.childcreateitemid) {
        ImmediateDetail(this.childcreateitemid).then((res) => {
          this.parentFlag = false
          this.parentList = res.data
          console.log(res.data);
          this.handleSelcetChange(res.data.acceptanceTypeId)
          console.log(this.ruleForm.acceAcceLevels);
          // this.PurchaseCheckList = this.parentList.purchaseEquipmentAccountVos
        })
      }
      this.purchaseList = res1
      this.optionsList = res2
      this.getuserList = res3
    },
    // 采购单数据转换给表单
    handlePurchaseListChange (purchaseId) {
      const dir = this.purchaseList.find(item => item.purchaseId == purchaseId)
      this.tableList = dir.purchaseEquipmentAccountVos
      this.ruleForm.acceptanceBase.purchaseId = dir.purchaseId
      this.ruleForm.acceptanceBase.purchaseNum = dir.purchaseNum
      this.ruleForm.acceptanceBase.purchaseTitle = dir.title
    },
    // 设备信息表格单选事件
    handleSelectionChange (selection, row) {
      if (selection.length) {
        if (selection.length === 1) {
          this.ruleForm.accePurEquips = selection[0]
        }
        if (selection.length > 1) {
          this.ruleForm.accePurEquips = selection[1] //purchaseEquipmentId
          // shift() 方法用于把数组的第一个元素从其中删除，并返回第一个元素的值。
          // 该方法不创建新数组，而是直接修改原有的 arrayObject。
          let del_row = selection.shift()
          // 其余的都不选中
          this.$refs.tableDataRefs.toggleRowSelection(del_row, false)
        }
      } else {
        this.ruleForm.accePurEquips = {}
      }

    },
    // 上传文件事件-------------------------------------------------------------------------------
    // handlesuccess (response, file, fileList) {
    //   if (response.code === 200) {
    //     this.ruleForm.file = response.data.url
    //   }
    //   this.fileList.push({
    //     name: file.name,
    //     url: file.response
    //   })
    // },
    // 删除上传的文件事件
    // handleremove (file, fileList) {
    //   var _tmp = this.fileList
    //   for (var i = 0; i < _tmp.length; i++) {
    //     if (_tmp[i].name === file.name) {
    //       _tmp.splice(i, 1)
    //       break
    //     }
    //   }
    //   this.fileList = _tmp
    // },
    // 文件上传之前的事件
    // beforeUpload (val) {
    //   const str = val.name.substring(val.name.lastIndexOf('.') + 1)
    //   const isLt2M = val.size / 1024 / 1024 < 50
    //   if (str !== 'xls' && str !== 'xlsx ' && str !== 'docx ' && str !== 'doc' && str !== 'pdf' && str !== 'jpg' && str !== 'png') {
    //     this.$message({
    //       message: '只能上传xls，xlsx ,.docx , .doc，.pdf，.jpg，.png文件,且不超过 50M',
    //       type: 'warning'
    //     })
    //     return false
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传文件大小不能超过 50MB!')
    //     return false
    //   }
    // },
    async handleSelcetChange (acceptanceType) {
      console.log(acceptanceType);
      const { data: res4 } = await checkList({ acceptanceType, status: 0 });// 验收标准接口
      this.PurchaseCheckList = res4;
      if (!this.childcreateitemid) {
        this.ruleForm.acceAcceLevels = []
      }
    },
    handleVisibleChange (visible) {
      if (visible) {
        if (this.childcreateitemid) {
          if (!this.parentList.acceptanceTypeName) {
            this.$message({
              message: '请先选择验收类型！',
              type: 'warning'
            });
            return false
          }

        } else {
          if (!this.ruleForm.acceptanceType) {
            this.$message({
              message: '请先选择验收类型！',
              type: 'warning'
            });
            return false
          }
        }
      }
    },
    // 表单总提交事件
    handleSubmitForm (status) {
      // console.log('Form总提交数据',this.ruleForm);
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (status && this.ruleForm.view == '') {
            this.$message.warning('验收不通过需要填写验收意见！');
            return
          }
          // --------------------------------------------新增验收------------------------------------------------
          if (this.parentFlag) {
            if (JSON.stringify(this.ruleForm.accePurEquips) !== '{}') {
              // -------------------------------------------------------重组表格列表提交数据--------------------------------------------
              const data = this.ruleForm
              // 重组表格数据-----------------
              const Equips = []
              Equips.push({
                purchaseEquipmentId: data.accePurEquips.purchaseEquipmentId
              })
              data.accePurEquips = Equips
              // 重组可多选验收标准数据-----------------
              data.acceAcceLevels = this.ruleForm.acceAcceLevels.map(item => {
                return {
                  acceptanceLevelId: item
                }
              })
              // 通过或未通过数据------------------
              data.status = status
              console.log('总表单重组后的数据', this.ruleForm.acceAcceLevels);
              add(data).then(() => {
                this.$emit('form_submit_click')
                this.$message.success('新增验收成功');
                this.handleRemove()
              })
            } else {
              this.$message.error('请选择设备信息，只可选一项');
            }
          } else {
            // --------------------------------------------立即验收------------------------------------------------
            const data = {
              acceptanceId: this.childcreateitemid,
              file: this.ruleForm.file,
              finalAcceptanceFlag: this.ruleForm.finalAcceptanceFlag,
              params: this.ruleForm.params,
              remark: this.ruleForm.remark,
              status: this.ruleForm.status,
              view: this.ruleForm.view,
              acceAcceLevels: this.ruleForm.acceAcceLevels.map(item => {
                return {
                  acceptanceLevelId: item
                }
              })
            }
            // 通过或未通过数据------------------
            data.status = status
            console.log('总表单重组后的数据', data);
            ImmediateDetailPut(data).then(() => {
              this.$emit('form_submit_click')
              this.$message.success('立即验收成功');
              this.handleRemove()
            })
          }

        } else {
          this.$message.error('提交表单验证信息不通过，请重新输入');
        }
      })


    },
    // 表单取消事件
    handleCloseForm () {
      this.$emit('form_submit_click')
      this.handleRemove()
    },
    // 表单过滤方法
    handleRemove () {
      for (const k in this.ruleForm.acceptanceBase) {
        this.ruleForm.acceptanceBase[k] = null
      }
      for (const k in this.ruleForm.params) {
        this.ruleForm.params[k] = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
// .dialog_left>div:nth-child(1){
//   flex:1
// }
// .dialog_left>div:nth-child(2) {
//   flex: 10;
//   margin-left: 10px
// }

/* el-descriptions-item 文字居中 */
::v-deep .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}

.rule-form {
  // width: 90%;
  // display: flex;
  // justify-content: space-between;
  // flex-wrap: wrap;
  // margin: 0 auto;

  .el-select {
    width: 300px;
  }

  .el-input {
    width: 300px;
  }
}

.rule_form_audit {
  width: 3%;
  margin: auto;
}

.dialog_btn {
  margin: 10px 45px;
}

.form_btn {
  width: 50%;
  display: flex;
  justify-content: space-between;
  margin: 50px auto 20px auto;

  .el-button {
    padding: 10px 40px;
    margin-left: 110px;
  }
}

// 禁掉全选按钮
::v-deep .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>